package com.sctvcloud.zhaohua_sd.ui.activities;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jiongbull.jlog.JLog;
import com.luck.picture.lib.PictureExternalPreviewActivity;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomFontEditText;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.OtherUtils;
import com.sctvcloud.zhaohua_sd.R;
import com.sctvcloud.zhaohua_sd.application.Cache;
import com.sctvcloud.zhaohua_sd.base.BaseActivity;
import com.sctvcloud.zhaohua_sd.application.Constances;
import com.sctvcloud.zhaohua_sd.beans.ContentImage;
import com.sctvcloud.zhaohua_sd.beans.CoverImage;
import com.sctvcloud.zhaohua_sd.beans.FUsers;
import com.sctvcloud.zhaohua_sd.beans.ImageUr;
import com.sctvcloud.zhaohua_sd.beans.SingleResult;
import com.sctvcloud.zhaohua_sd.http.AbsNetCallBack;
import com.sctvcloud.zhaohua_sd.http.NetUtils;
import com.sctvcloud.zhaohua_sd.http.ParamsEditor;
import com.sctvcloud.zhaohua_sd.ui.adapter.RebllionCommitAdapter;
import com.sctvcloud.zhaohua_sd.ui.dialog.PicChoiceDiaFragment;
import com.sctvcloud.zhaohua_sd.ui.dialog.ShotChoiceDiaFragment;
import com.sctvcloud.zhaohua_sd.ui.utils.KeyBoardUtils;
import com.sctvcloud.zhaohua_sd.ui.utils.PictureUtils;
import com.sctvcloud.zhaohua_sd.ui.utils.TitleUtils;
import com.sctvcloud.zhaohua_sd.ui.utils.UiListMarginUtils;
import com.sctvcloud.zhaohua_sd.utils.UserManager;
import com.sctvcloud.zhaohua_sd.utils.VideoCompressAsyncTask;

import java.io.File;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wseemann.media.FFmpegMediaMetadataRetriever;

/**
 * 分享主播页
 */
public class ShareAnchorActivity extends BaseActivity implements RebllionCommitAdapter.RemainListSize, TextWatcher {
    @BindView(R.id.title_top_edit)
    protected CustomFontTextView publish;
    @BindView(R.id.share_anchor_content)
    protected CustomFontEditText content_ct;
    @BindView(R.id.share_anchor_pic_prompt)
    protected CustomFontTextView prompt;
    @BindView(R.id.share_anchor_pic_list)
    protected RecyclerView pic_list;
    private PicChoiceDiaFragment picChoiceDiaFragment;
    public static final String PIC_TAG = "dia_pic_choice_fragment";
    public static final String SHOT_TAG = "dia_shot_choice_fragment";
    private GridLayoutManager manager;
    private RebllionCommitAdapter adapter;
    private List<LocalMedia> selectList = new ArrayList<>();

    private int maxSelectNum = 9;
    private int type = 0;  //type为0 拍照 1 录像 2图片
    private List<LocalMedia> currentList = new ArrayList<>();
    private int themeId;
    private boolean isLongClick = true;
    private ShotChoiceDiaFragment shotChoiceDiaFragment;
    private FUsers mFUsers;
    public static final int REQUEST_CODE = 16;
    private int pictureType;
    //    private String coverImage;
    private String videoUrl;
    private String coverImageUrl;
    private String imgUrl;
    private JsonArray images;
    private int user_type = Constances.USER_TYPE_ANCHOR;  //1普通用户 2小编 3 主播(只有主播才能发布主播圈)
    private CoverImage coverImage;
    private ArrayList<ContentImage> contentImages = new ArrayList<>();
    private Handler compressHandler;
    private boolean isCompressing = false;
    private boolean isInCurrentPage = false;
    private boolean isCompressSuccess = true;
    private String compressPath = "";//视频压缩后的地址
    private boolean isPublishing = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        themeId = R.style.picture_default_style;
        compressHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (null != msg) {
                    int what = msg.what;
                    switch (what) {
                        case VideoCompressAsyncTask.COMPRESS_SUCCESS:
                            isCompressing = false;
//                            closeProgress();
                            toast("压缩成功");
//                            SingleToast.getInstance(RebllionCommitActivity.this).showCenterToast("压缩成功");
                            compressPath = (String) msg.obj;
                            isCompressSuccess = true;
                            uploadVideo();
                            break;
                        case VideoCompressAsyncTask.COMPRESS_ERROR:
//                            closeProgress();
                            toast("压缩失败");
//                            SingleToast.getInstance(RebllionCommitActivity.this).showCenterToast("视频压缩失败，请重试");
                            compressPath = (String) msg.obj;
                            isCompressing = false;
                            isCompressSuccess = false;
                            uploadVideo();
                            break;
                    }
                }
            }
        };
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_share_anchor);
        ButterKnife.bind(this);
    }

    @Override
    protected void onUserExpired() {
        setResult(1);
        toLogin();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isPublishing) {
            showProgress(getString(R.string.share_anchor_wait), true);
        } else if (isCompressing) {
            showProgress("视频处理中，请勿退出或关闭屏幕", true);
        }
        isInCurrentPage = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        closeProgress();
        isInCurrentPage = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isInCurrentPage = false;
        closeProgress();
        Cache.getInstance().setUploadReb(false);
    }

    @Override
    protected void onLoginSuc() {
        super.onLoginSuc();
    }

//    public void onBackPressed() {
//        if (!isCompressing) {
//            super.onBackPressed();
//            ShareAnchorActivity.this.finish();
//        }
//
//    }

    private void initView() {
//        ImageView backImg = (ImageView) findViewById(R.id.title_top_back);
//        if (null != backImg) {
//            backImg.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    if (!isCompressing) {
//                        ShareAnchorActivity.this.finish();
//                    }
//                }
//            });
//        }
        publish.setVisibility(View.VISIBLE);
        publish.setText(getString(R.string.rebllion_publish));
        publish.setTextColor(getResources().getColor(R.color.colorUpdate));
        manager = new GridLayoutManager(this, 3);
        pic_list.setItemAnimator(new DefaultItemAnimator());
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        pic_list.setHasFixedSize(true);
        pic_list.setNestedScrollingEnabled(false);
        pic_list.setLayoutManager(manager);
        new UiListMarginUtils().setMargin(this, pic_list, R.dimen.item_list_large_margin_left, R.dimen.item_list_large_margin_right);
        content_ct.addTextChangedListener(this);
        if (adapter == null) {
            adapter = new RebllionCommitAdapter(this, selectList).setItemInternalClick(picItemClick).setRemainListSize(this);
            adapter.setOnLongItemClick(onLongClick);
            pic_list.setAdapter(adapter);
        }
    }

    @OnClick(value = {R.id.title_top_edit})
    public void publishClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_edit:
                if (TextUtils.isEmpty(content_ct.getText().toString())) {
                    toast(R.string.share_content_empty);
                    return;
                }
                if (UserManager.getInstance().isLogin()) {
                    mFUsers = UserManager.getInstance().getUser();
                    int userType = mFUsers.getUserType();
                    if (userType == user_type) {
                        Cache.getInstance().setUploadReb(true);
                        if (selectList.size() > 0) {
                            KeyBoardUtils.closeKeyboard(ShareAnchorActivity.this);
                            pictureType = PictureMimeType.isPictureType(selectList.get(0).getPictureType());
                            if (pictureType == PictureMimeType.ofVideo()) {
                                String videoPath = compressPath;
                                JLog.e("rrsr  video path=" + videoPath);
                                if (!TextUtils.isEmpty(videoPath)) {
                                    File file = new File(videoPath);
                                    double size = OtherUtils.getFileSize(file);
                                    size = size / 1024 / 1024;
                                    JLog.e("rrsr size=" + size);
                                }
                            }
                            upLoadingImage();
                        } else {
                            publish();
                        }
                    } else {
                        toast(R.string.share_anchor_no_anchor);
                    }

                } else {
                    // toast(R.string.mine_no_login);
                    toLogin();
                }


                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    if (type == 0) {
                        currentList.addAll(selectList);
                        selectList = currentList;
                        if (adapter.getEqualDatas() == selectList) {
                            adapter.notifyDataSetChanged();
                        } else {
                            adapter.setData(selectList);
                        }

                    } else if (type == 1) {
                        adapter.setData(selectList);
//                        if (null != selectList && selectList.size() > 0 && !TextUtils.isEmpty(selectList.get(0).getPath())) {
//                            //压缩视频
//                            compressVideo(selectList.get(0));
//                        }
                    } else if (type == 2) {
                        adapter.setData(selectList);
                        currentList.clear();
                        currentList.addAll(selectList);
//                        if (null != selectList && selectList.size() > 0 && selectList.get(0).getPictureType().equalsIgnoreCase("video/mp4")
//                                && !TextUtils.isEmpty(selectList.get(0).getPath())) {
//                            //压缩视频
//                            compressVideo(selectList.get(0));
//                        }
                    }
                    break;
                case REQUEST_CODE:
                    int pos = data.getIntExtra(PictureExternalPreviewActivity.POS, 0);
                    if (pos > 0) {
                        selectList = (List<LocalMedia>) data.getSerializableExtra(PictureExternalPreviewActivity.PIC_LIST);
                        adapter.setData(selectList);
                    } else {
                        adapter.clean();
                        selectList.clear();
                    }
                    break;
            }
        }
    }

    BaseDialogFragment.ICallBack picCallBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == 1) {
                if (selectList.size() != 0) {
                    int pictureType = PictureMimeType.isPictureType(selectList.get(0).getPictureType());
                    if (pictureType == 2 && selectList.size() == 1) {
                        toast("只能选择一个视频");
                    } else {
                        getShotDiaFragment();
                    }
                } else {
                    getShotDiaFragment();
                }
            } else if (msg.what == 2) {
                type = 2;
                PictureUtils.choicePic(ShareAnchorActivity.this, themeId, selectList);
            }
        }
    };

    private void getShotDiaFragment() {
        if (shotChoiceDiaFragment == null) {
            shotChoiceDiaFragment = new ShotChoiceDiaFragment();
        }
        shotChoiceDiaFragment.setCallBack(shotCallBack);
        shotChoiceDiaFragment.show(getSupportFragmentManager(), SHOT_TAG);
    }

    OnItemInternalClick picItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            if (position == adapter.getItemCount() - 1) {
                if (selectList.size() < 9) {
                    if (picChoiceDiaFragment == null) {
                        picChoiceDiaFragment = new PicChoiceDiaFragment();
                    }
                    picChoiceDiaFragment.setCallBack(picCallBack);
                    picChoiceDiaFragment.show(getSupportFragmentManager(), PIC_TAG);
                    prompt.setVisibility(View.GONE);
                } else {
                    toast(getString(R.string.rebllion_publish_pic_total));
                }

            } else {
                LocalMedia media = adapter.getItem(position);
                String pictureType = media.getPictureType();
                int mediaType = PictureMimeType.pictureToVideo(pictureType);
                switch (mediaType) {
                    case 1:
                        // 预览图片 可自定长按保存路径
                        Intent intent = new Intent(ShareAnchorActivity.this, PictureExternalPreviewActivity.class);
                        intent.putExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST, (Serializable) selectList);
                        intent.putExtra(PictureConfig.EXTRA_POSITION, position);
                        intent.putExtra(PictureConfig.DIRECTORY_PATH, "/custom_file");
                        startActivityForResult(intent, REQUEST_CODE);
                        overridePendingTransition(com.luck.picture.lib.R.anim.a5, 0);
                        break;
                    case 2:
                        // 预览视频
                        PictureSelector.create(ShareAnchorActivity.this).externalPictureVideo(media.getPath());
                        break;
                    case 3:
                        // 预览音频
                        PictureSelector.create(ShareAnchorActivity.this).externalPictureAudio(media.getPath());
                        break;
                }
            }
        }
    };

    OnItemInternalClick onLongClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            if (isLongClick) {
                adapter.setEdting(true);
                isLongClick = false;
            } else {
                adapter.setEdting(false);
                isLongClick = true;
            }
        }
    };
    BaseDialogFragment.ICallBack shotCallBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == 1) {
                type = 0;
                PictureUtils.choicePhoto(ShareAnchorActivity.this);
            } else if (msg.what == 2) {
                type = 1;
                if (selectList != null) {
                    selectList.clear();
                }
                PictureUtils.choiceVideo(ShareAnchorActivity.this);
            }
        }
    };
    //默认视频缓存文件夹
    private static final String VIDEO_PATH = Environment.getExternalStorageDirectory().getPath() + PictureFileUtils.CAMERA_VIDEO_PATH;

    /**
     * 压缩视频
     *
     * @param video
     */

    private void compressVideo(LocalMedia video) {
        showProgress("视频处理中，请勿退出或关闭屏幕", false);
        keepWindowOn(true);
        isCompressing = true;
        isCompressSuccess = false;
        try {
            File fileNew = new File(VIDEO_PATH);
            if (!fileNew.exists()) {
                fileNew.mkdirs();
            }

            //compress and output new video specs
            new VideoCompressAsyncTask(this, compressHandler).execute(video.getPath(), fileNew.getPath());
        } catch (Exception e) {
            e.printStackTrace();
            keepWindowOn(false);
        }
    }

    /**
     * 从Path中截取文件名称
     *
     * @param url
     * @return
     */
    public static String getVideoName(String url) {
        String name = "";
        if (!TextUtils.isEmpty(url)) {
            String[] nList = url.split("/");
            if (null != nList && nList.length > 0) {
                String n = nList[nList.length - 1];
//                int in = n.indexOf(".");
                name = n;//n.substring(0,in);
            }
        }
        return name;
    }

    @Override
    public void getRemainListSize(List<LocalMedia> list) {
        selectList = list;
        currentList = list;
        adapter.notifyDataSetChanged();
    }


    private void upLoadingImage() {
//        if (isCompressing) {
//            SingleToast.getInstance(this).showCenterToast("正在压缩视频，请稍等...");
//            return;
//        }
        if (pictureType == PictureMimeType.ofVideo()) {
            //如果爆料的是视频内容，先压缩再上传
            if (null != selectList && selectList.size() > 0 && !TextUtils.isEmpty(selectList.get(0).getPath())) {
                if (!TextUtils.isEmpty(compressPath) && isCompressSuccess) {
                    File file = new File(compressPath);
                    if (file.exists()) {
                        uploadVideo();
                        return;
                    }
                }
                //压缩视频
                compressVideo(selectList.get(0));
            }
        } else if (pictureType == PictureMimeType.ofImage()) {
            contentImages = new ArrayList<>();
            for (LocalMedia localMedia : selectList) {
                ContentImage contentImage = new ContentImage();
                if (TextUtils.isEmpty(localMedia.getCompressPath())) {
                    contentImage.setImageUrl(localMedia.getPath());
                } else {
                    contentImage.setImageUrl(localMedia.getCompressPath());
                }
                contentImage.setWidth(localMedia.getWidth());
                contentImage.setHeight(localMedia.getHeight());
                contentImages.add(contentImage);
            }
            isPublishing = true;
            showProgress(getString(R.string.share_anchor_wait), false);
            NetUtils.getNetAdapter().uploadImages(getOwnerName(), contentImages, new AbsNetCallBack<SingleResult>(SingleResult.class) {
                @Override
                public void onSuc(SingleResult singleResult) {
                    if (singleResult != null && singleResult.getImages() != null) {
                        getImagesURL(singleResult.getImages(), contentImages);
                    }
                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    super.onError(ex, errorMsg);
                    JLog.e("===error==" + errorMsg);
                    toast(R.string.share_anchor_pic_fail);
                    closeProgress();
                    keepWindowOn(false);
                    isPublishing = false;
                }

                @Override
                public void onEnd() {
                    super.onEnd();

                }
            });
        }

    }

    /**
     * 视频压缩完成，开始上传视频封面
     */
    private void uploadVideo() {
        contentImages = new ArrayList<>();
        coverImage = getFirstFrameFromVideo(compressPath);
        ContentImage contentImage = new ContentImage();
        contentImage.setHeight(coverImage.getHeight());
        contentImage.setWidth(coverImage.getWidth());
        contentImage.setImageUrl(coverImage.getImageUrl());
        contentImages.add(contentImage);
        isPublishing = true;
        showProgress(getString(R.string.share_anchor_wait), false);
        NetUtils.getNetAdapter().uploadImages(getOwnerName(), contentImages, new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onSuc(SingleResult singleResult) {
                if (singleResult != null && singleResult.getImages() != null) {
                    getImagesURL(singleResult.getImages(), contentImages);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                JLog.e("===error==" + errorMsg);
                toast(R.string.share_anchor_video_pic_fail);
                closeProgress();
                isPublishing = false;
                keepWindowOn(false);
            }
        });
    }

    /**
     * 切换设置屏幕常亮状态
     *
     * @param isKeep 是否常亮
     */
    private void keepWindowOn(boolean isKeep) {
        if (isKeep) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    }

    private void deleteTempVideo() {
        if (!TextUtils.isEmpty(compressPath) && isCompressSuccess) {
            File file = new File(compressPath);
            if (file.exists()) {
                file.delete();
            }
        }
        compressPath = "";
    }

    private void upLoadVideo() {
        String videoPath = compressPath;
        if (!TextUtils.isEmpty(videoPath)) {
            NetUtils.getNetAdapter().uploadVideo(getOwnerName(), videoPath, new AbsNetCallBack<SingleResult>(SingleResult.class) {
                @Override
                public void onSuc(SingleResult singleResult) {
                    if (singleResult != null) {
                        videoUrl = singleResult.getVideoUrl();
                        publish();
                        deleteTempVideo();
                    }
                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    super.onError(ex, errorMsg);
                    toast(R.string.share_anchor_video_fail);
                    closeProgress();
                    isPublishing = false;
                    Cache.getInstance().setUploadReb(false);
                    keepWindowOn(false);
                }

            });
        }

    }

    private void getImagesURL(JsonArray images, ArrayList<ContentImage> imgs) {
        if (images.size() == 0) {
            toast(R.string.data_wrong);
            closeProgress();
            isPublishing = false;
            return;
        }
        if (pictureType == PictureMimeType.ofVideo()) {
            coverImageUrl = images.get(0).getAsJsonObject().get("imageUrl").getAsString();
//            imgs.get(0).setImageUrl(coverImageUrl);
            coverImage.setImageUrl(coverImageUrl);
//            coverImageUrl = images.toString();
            upLoadVideo();
        } else if (pictureType == PictureMimeType.ofImage()) {
            this.images = images;
            ArrayList<ImageUr> imageUrs = new Gson().fromJson(images, new TypeToken<List<ImageUr>>() {
            }.getType());
            for (int i = 0; i < imgs.size(); i++) {
                imgs.get(i).setImageUrl(imageUrs.get(i).getImageUrl());
            }
            publish();
        }

    }

    /**
     * 发布上传
     */
    public void publish() {

        ParamsEditor pe = new ParamsEditor();//注意,参数的添加须有前后顺序
        if (selectList.size() > 0) {
            if (pictureType == PictureMimeType.ofVideo()) {
                pe.put("contentText", content_ct.getText().toString());
                pe.put("contentVideo", videoUrl);
                JsonObject jsonObject = new Gson().toJsonTree(coverImage).getAsJsonObject();
                pe.put("videoImage", jsonObject);
            } else {
                JsonArray jsonArray = new Gson().toJsonTree(contentImages, new TypeToken<List<ContentImage>>() {
                }.getType()).getAsJsonArray();
                pe.put("contentImages", jsonArray);
                pe.put("contentText", content_ct.getText().toString());
            }
        } else {
            pe.put("contentText", content_ct.getText().toString());
        }

        pe.put("userId", mFUsers.getUserId());
        pe.put("siteNumber", Constances.SITE_ID);

        NetUtils.getNetAdapter().postAnchor(getOwnerName(), pe.getEncryptedParams(mFUsers.getToken())
                , new AbsNetCallBack<SingleResult>(Boolean.class) {
                    @Override
                    public void onSuc(SingleResult singleResult) {
                        if (singleResult == null || !singleResult.isSuccess()) {
                            toast(R.string.share_anchor_publish_failure);
                        } else {
                            toast(R.string.share_anchor_publish_succ);
                            mApplication.getDatasVersionManager().updateVersion(Constances.DATA_VERSION_ADYNAMIC);
                            finish();
                        }
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        JLog.e("====error==" + errorMsg);
                        toast(R.string.share_anchor_publish_failure);
                    }

                    @Override
                    public void onEnd() {
                        Cache.getInstance().setUploadReb(false);
                        if (pictureType == PictureMimeType.ofVideo()) {
                            deleteVideoCoverImage();
                        }
                        closeProgress();
                        keepWindowOn(false);
                    }
                });


    }

    private FFmpegMediaMetadataRetriever media;

    private CoverImage getFirstFrameFromVideo(String videoPath) {
        //获取第一帧图像的bitmap对象
        Bitmap bitmap;
        int width = 0;
        int height = 0;
        try {
            // 获取视频的缩略图
            bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Images.Thumbnails.MINI_KIND); //調用ThumbnailUtils類的靜態方法createVideoThumbnail獲取視頻的截圖；
            if (bitmap == null) {
                media = new FFmpegMediaMetadataRetriever();
                media.setDataSource(videoPath);
                bitmap = media.getFrameAtTime(100, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
                if (bitmap == null) {
                    return null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        try {
            //当文件未创建时，先创建文件夹。之后再创建图片文件
            String path = Environment.getExternalStorageDirectory().getPath() + PictureFileUtils.CAMERA_PIC_PATH;
            File fileNew = new File(path);
            if (!fileNew.exists()) {
                fileNew.mkdirs();
            }
            File file = new File(fileNew, "CoverCut_" + System
                    .currentTimeMillis() + ".jpeg");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            width = bitmap.getWidth();
            height = bitmap.getHeight();
            out.flush();
            out.close();
            CoverImage coverImage = new CoverImage();
            coverImage.setImageUrl(file.getAbsolutePath());
            coverImage.setHeight(height);
            coverImage.setWidth(width);
            return coverImage;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    private void deleteVideoCoverImage() {
        if (!TextUtils.isEmpty(coverImage.getImageUrl())) {
            File file = new File(coverImage.getImageUrl());
            if (file.exists()) {
                file.delete();
                coverImage = null;
            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        int length = getStrLength(s.toString());
        if (length == 120) {
            toast(R.string.only_120_word);
        }
    }

    private int getStrLength(String str) {
        if (str == null) {
            return 0;
        }
        return str.length();
    }
}
